package com.litchi.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import javax.annotation.PostConstruct;

/**
 * @Author: Jiangxx
 * @Date: 2023/08/28
 * @Description:
 */
@Slf4j
@Component
public class KafkaProducerService {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public final ObjectMapper mapper = new ObjectMapper();

    @PostConstruct
    public void init() {
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        mapper.registerModule(new JavaTimeModule());
    }


    public void sendWithConversion(String topic, String key, Object object) throws Exception {

        String sendData = mapper.writeValueAsString(object);

        baseSend(topic, key, sendData);
    }

    public void send(String topic, String object) {
        baseSend(topic, null, object);
    }

    public void baseSend(String topic, String key, String data) {

        ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(topic, key, data);

        // 回调：打印结果信息
        future.addCallback(new ListenableFutureCallback<>() {
            @Override
            public void onSuccess(SendResult<String, String> result) {
                log.info("发送消息成功: " + result.toString());
            }

            @Override
            public void onFailure(Throwable throwable) {
                log.error("发送消息失败: " + throwable.getMessage());
            }
        });
    }
}
